﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace SnippetBox.Core.Common.Paging.Simple {
    public static class SimplePaging {
        private const string KEY_CURRENT_PAGE = "__paging_CurrentPage";
        private const string KEY_TOTAL_PAGES = "__paging_TotalPages";
        private const string KEY_ITEM_COUNT = "__paging_ItemCount";

        public static List<T> ToSimplePaging<T>(this IQueryable<T> query, int? index, int pageSize) {
            return ToSimplePaging(query, index, pageSize, null);
        }

        public static List<T> ToSimplePaging<T>(this IQueryable<T> query, int? index, int pageSize,
                                                Controller controller) {
            var pageIndex = index.HasValue ? index.Value - 1 : 0;
            var skipPosts = pageSize*pageIndex;

            if (controller != null) {
                int items = query.Count();
                controller.ViewData[KEY_CURRENT_PAGE] = pageIndex + 1;
                controller.ViewData[KEY_TOTAL_PAGES] = Math.Ceiling((double) items/pageSize);
                controller.ViewData[KEY_ITEM_COUNT] = items;
            }

            if (pageIndex < 0)
                return new List<T>();

            return query.Skip(skipPosts).Take(pageSize).ToList();
        }

        public static PagingInfo PagingInfo(this HtmlHelper html) {
            try {
                int currentPage = int.Parse(html.ViewData[KEY_CURRENT_PAGE].ToString());
                int totalPages = int.Parse(html.ViewData[KEY_TOTAL_PAGES].ToString());
                int itemCount = int.Parse(html.ViewData[KEY_ITEM_COUNT].ToString());

                return new PagingInfo(currentPage, totalPages, itemCount);
            }
            catch {
                return new PagingInfo(0, 0, 0);
            }
        }
    }

    public class PagingInfo {
        public int CurrentPage { get; set; }
        public int TotalPages { get; set; }
        public int ItemCount { get; set; }

        public int NextPage {
            get { return CurrentPage + 1; }
        }

        public int PreviousPage {
            get { return CurrentPage - 1; }
        }

        public bool HasNextPage {
            get { return NextPage <= TotalPages; }
        }

        public bool HasPreviousPage {
            get { return PreviousPage > 0; }
        }

        public PagingInfo(int currentPage, int totalPages, int itemCount) {
            CurrentPage = currentPage;
            TotalPages = totalPages;
            ItemCount = itemCount;
        }
    }
}